<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns:fb="http://www.facebook.com/2008/fbml">

<head>

<script type="text/javascript" src="/scripts/constants.js"></script>
<script type="text/javascript" src="/scripts/fill-template-scripts.js"></script>
<script type="text/javascript" src="/scripts/localstoragedb.js"></script>
<script type="text/javascript" src="/scripts/library-scripts.js"></script>

<!-- script type="text/javascript" src="/scripts/JSON-parse.js"  -->
<script type="text/javascript" src="/scripts/handlebars.1.0.0.beta.3.js"></script>
<script type="text/javascript" src="/scripts/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="/scripts/jquery.cuteTime.min.js"></script>
<script type="text/javascript" src="/scripts/encoder.js" ></script>

<link rel="stylesheet" href="/css/bootstrap-1.2.0.min.css">
<link rel="stylesheet" href="/css/custom-styles.css">

<title>Crawl shopping web-sites and capture deals</title>

<meta name="description" content="Browse one of the worlds largest shopping deals database"/>
<meta name="keywords" content="shopping deals shoppingdeals dailydeals electronics price tracking price history christmas thanksgiving deal deals archive archive nintendo wii samsung tv xbox kinect laptop computer"/>

</head>

<script type="text/javascript">
extendFeatures();

var urlParams = $.getUrlVars();
if (urlParams['editor-deal-id']) {
	window.location = "/shopping-resources.html?editor-deal-id=" +
					  unescape(urlParams['editor-deal-id']) + "";	
}

</script>

<script id="deal-entry-template" type="text/x-handlebars-template">
	{{#each deals}}
		<tr>
			<td>
				{{{showBookmark}}}
			</td>
			<td>
				{{#if this.dealId}}
				<div id="{{this.dealId}}">
				{{else}}
				<div>
				{{/if}}
					<a title="{{{this.title}}}" target="_blank"
						{{#if this.link}} 
							href="{{this.link}}">
						{{else}}
							href="http://api-dealscrawler.apigee.com/deals/url?id={{this.dealId}}">
						{{/if}}
						{{{trimTitle}}}
					</a>
					&nbsp;
					<span class="timestamp">{{this.pubDate}}</span>
				</div>
			</td>
		</tr>
	{{/each}}
</script>

<script type="text/javascript">
Handlebars.registerHelper('trimTitle', function() {
	var tempTitle = this.title;
	if (tempTitle && tempTitle.length > titleMaxLength && !dealId) {
    	return tempTitle.slice(0, titleMaxLength - 5) + " ....";
	} else {
		return tempTitle;
	}
});

Handlebars.registerHelper('showBookmark', function() {
	if (bookmarkServiceEnabled) {
		return buildStarDivHTML(this.dealId, 'starIt');
	} else {
		return '<div>&nbsp;</div>';
	}
});
</script>

<script type="text/javascript">

var serverNextPageNumber = 0;
var defaultServlet = "/deals";
var defaultServletParams = "?format=json";
var baseDealsURL = dealsDBHostName + defaultServlet + defaultServletParams;
var allDeals = {};
var dealId = false;
var dealsTableTemplateHTMLLoaded = false;
var extensionMode = false;

var handleBarsSource;
var handleBarsTemplate;

function openChromeTab(targetLink)
{
	try {
		chrome.tabs.create({url:targetLink, active: false});
	} catch(e) {
		// Ignore
	}
	return false;
}

function cleanSlate() {
	$('#content').html('');		
	allDeals = {};
	dealsTableTemplateHTMLLoaded = false;		   
	serverNextPageNumber = 0;
}

function decorateInterface(elementSelector, title) {
	$(elementSelector).addClass('active');		
	document.title = title;
	cleanSlate();	
}

function prepareDefaultServletParams() {
	if (urlParams['feedId']) {
		defaultServletParams += "&feedId=" + urlVars['feedId'];
	}	
}

function retrieveBookmarkedDeals() {
	decorateInterface('.starred-items-tab', 'Bookmarked Deals');
  		
	if (!browserSupported) {
		$('#content').html(notSupportedMessageHTML);
		return;
	}
	
	if (!bookmarkServiceEnabled) {
		$('#content').html(noBookmarkServiceMessageHTML);
		return;
	}

	try {
		var bookmarkedDeals = databaseHandle.query(bookmarksTableName);
		if (bookmarkedDeals.length == 0) {
			$('#content').html(noStarredItemsMessageHTML);
			return;
		}
		for (i = 0; i < bookmarkedDeals.length; i++) {
			allDeals[bookmarkedDeals[i].dealId] = bookmarkedDeals[i];
		}
		showPageDeals(bookmarkedDeals, false);
		$('.star').addClass('on');
	    $('#moreDealsDiv').remove();
	} catch (e) {
		// Ignore for now
	}
}

function prepareForInfiniteScrolling() {
	if (urlParams['isc'] == 1) {
		// Copied from http://www.webresourcesdepot.com/load-content-while-scrolling-with-jquery/
		$(window).scroll(function(){
			if  ($(window).scrollTop() == $(document).height() - $(window).height()){
			   if ($('#moreDealsDiv')) {
			   	  retrieveDeals();
			   }
			}
		});
	}	
}

function retrieveHotDeals() {
	decorateInterface('.hot-items-tab', 'Hot Shopping Deals');	
	baseDealsURL = 	dealsDBHostName + "/HotDeals" + defaultServletParams;
	retrieveDeals();
}

function getSpecificDeal(dealId) {
	cleanSlate();
	baseDealsURL = baseDealsURL + "&id=" + dealId; 	
	retrieveDeals();
}

function showArchiveDealsInterface() {	
	if (dealsDBHostName == '') {
		bookmarkServiceEnabled = false;
	}

	decorateInterface('.deals-archive-tab', 'Archived Deals');
	$('#menuTable').html(sidebarArchiveDealsHTMLCode);

	$("#searchTermInput").keyup(function (e) {
		  if (e.keyCode == 13) {
		    $(this).trigger("enter");
		  }
		}).bind("enter", function () {
		  searchDeals();
		});	
}

function retrieveRegularDeals() {
	decorateInterface('.home-tab', document.title);
	retrieveDeals();			
}

function searchDeals()
{
	var searchTerms = $('#searchTermInput').val();
	searchTerms = (searchTerms) ? $.trim(searchTerms) : "";	
	if (searchTerms.match(/^\d\d\d\d-\d\d-\d\d$/)) {
		baseDealsURL = dealsDBHostName + defaultServlet + defaultServletParams +
					   '&startDate='+searchTerms+
					   '&endDate='+searchTerms+
					   '&newQuery=yes';		
		retrieveDeals();
	} else {
		$('#result').html("Please enter the date in the correct format");
		return;
	}
}

function retrieveDeals()
{   
	$('#result').html('Retrieving the shopping deals. '+
    				  '<img src="images/spinner.gif" alt="Processing"/>');
   if (dealsDBHostName == '') {
	   $.ajax({
	      url : baseDealsURL + "&page=" + serverNextPageNumber,
	      success : jsonDealsFeed,
	      error : function(data) { $('#result').html('Error while retrieving the deals'); scroll(0,0);}
	   });
   } else {
		$.getJSON(baseDealsURL + "&jsoncallback=?&page=" + serverNextPageNumber, jsonDealsFeed);
   }
}

function showNoDealsMessage() {
   if (!dealId) {
      $('#result').html("No more Deals found :(");
   } else {
	  $('#result').html('');
	  $('#content').html(NO_DEAL_FOUND_WARNING_HTML);
   }
   scroll(0,0);
}

function jsonDealsFeed (data) {
	   var length = 0;
	   var deals = undefined;
	   
       try {
		   var jsonObject = data;
		   if (dealsDBHostName == '') {
			    //jsonObject = json_parse(data);
		   }
		   
		   if (jsonObject) {
			   deals = jsonObject.deals;
			   if (deals) {
			      length = deals.length;
		   		}
		   }
	
		   if (length <= 0) {
			   showNoDealsMessage();
			   return;
		   }

       } catch (err) {
           // Ignore this result and try the next page. Something got screwed up in JSON parsing.
    	   //serverNextPageNumber++;
		   //retrieveDeals();
		   //console.log(err);
			showNoDealsMessage();
			return;
       }
       for (i = 0; i < length ; i++) {
           try {
               deals[i].title = unescape(deals[i].title);
               deals[i].title = Encoder.htmlDecode(deals[i].title);
    		   //deals[i].pubDate = dateFormat(deals[i].pubDate, "mmm dd yyyy, HH:mm:ss");               
           } catch (e) {
				// Ignore the error if the unescape fails.
				//console.log(e);
           }
           deals[i].title = $.trim(deals[i].title);
           deals[i].pubDate = $.trim(deals[i].pubDate);
           allDeals[deals[i].dealId] = deals[i];
       }
       serverNextPageNumber++;
       showPageDeals(deals, true);		   
}

function showPageDeals(deals, starItems) {
	   if (deals) {
		   var newDealsHTML = handleBarsTemplate({"deals": deals});
		   //console.log(newDealsHTML);
		   
		   if (!dealsTableTemplateHTMLLoaded) {
			   $(dealsTableTemplateHTMLCode).appendTo($('#content'));
			   dealsTableTemplateHTMLLoaded = true;
		   }		   
		   
		   var jQueryNewDeals = $(newDealsHTML);

		   if (extensionMode) {
				jQueryNewDeals.find('a').each(function(index, element) {
					var targetLink = $(element).attr('href');
					$(element).attr('href', '#');
					$(element).attr('onclick', "openChromeTab('" + targetLink + "'); return false;");
				});
		   }
		   
		   jQueryNewDeals.insertAfter($('#dealsTable tr:last'));
		   $('.timestamp').cuteTime(cuteTimeSettings);
		   if (bookmarkServiceEnabled && starItems) {
			   jQueryNewDeals.find('div.star').each(function (index) {
				  try {
				     var idParam = $(this).attr('id').slice(1);
				     if (databaseHandle.query(bookmarksTableName, {"dealId": idParam}).length) {
						$(this).addClass('on');
				     }
				  } catch (e) {
					  //console(e);
					  // Lets ignore this for now
				  }
			   });
		   }
		 $('#result').html('');
		 // Ideally we should check the following block whenever we update
		 // the deals table. But just embedding the check in this if block
		 // should be sufficient. Hopefully, the first call to deals
		 // servlet should return proper number of deals.
	   } else {	  
			showNoDealsMessage();
			return;
	   }

	   if (dealId) {
		   // No more button for displaying an individual deal id.
		   $('#moreDealsDiv').remove();
		   $('#dealsTableDiv').removeClass('row');
		   var fbcommentsHTML = getFBCommentsHTML(window.location);
		   $(fbcommentsHTML).appendTo($('#content'));
		   loadFBCommentsScript();
		   document.title = deals[0].title;
	   }
	   
	   return;
}

function documentLoadedReady() {
	handleBarsSource   = $("#deal-entry-template").html();
	handleBarsTemplate = Handlebars.compile(handleBarsSource);

	if (urlParams['extension'] == 1) {
		extensionMode = true;
		loadExtensionTemplate();
		callExtensionGoogleAnalyticsScript();
		retrieveRegularDeals();
		return;
	}
	
	loadAllHTMLBlocks();
	bookmarkServiceEnabled = loadBookmarkService();

	prepareDefaultServletParams();
	prepareForInfiniteScrolling();

	if (urlParams['bookmark'] == 1) {
		retrieveBookmarkedDeals();
	} else if (urlParams['hot-deals'] == 1) {
		retrieveHotDeals();		
	} else if (urlParams['archive'] == 1) {
		showArchiveDealsInterface();
	} else if ((dealId = urlParams['id'])) {
		getSpecificDeal(dealId);
	} else {
		retrieveRegularDeals();
	}
		
	loadAllBasicScripts();
}
</script>

<body>
	<div id="firstDiv" align="center" class="container">
		<div id="preContentBlock">
		</div>
		<br/>
		<div class="container-fluid">
			<div id="sidebar" class="sidebar">
			</div>
			<div id="content" class="content">			
			</div>
			<br/>
			<br/>
		</div>	
	</div>
</body>

<script type="text/javascript">
	jQuery(document).ready(documentLoadedReady);
</script>

</html>